<template>
	<div class="page">
    <div class="card chat-shell" style="padding:8px;">
			<div>当前会话 ID：<code>{{ chatId }}</code></div>
		</div>
		<div class="card chat-shell">
			<ChatRoom ref="roomRef" :startStream="startLoveStream" aiAvatar="💘" userAvatar="🙂" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import ChatRoom from '../components/ChatRoom.vue';
import { useSeo } from '../composables/useSeo';

const roomRef = ref<InstanceType<typeof ChatRoom> | null>(null);
const chatId = ref('');

function generateChatId() {
	return 'chat_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
}

onMounted(() => {
	chatId.value = generateChatId();
});

useSeo({ title: 'AI 恋爱大师 - 流式对话', description: '恋爱沟通建议，SSE 流式输出，支持多会话 chatId', keywords: '恋爱大师, AI, SSE, chatId' });

// 启动 SSE：调用 /ai/love_app/chat/sse?message=&chatId=
function startLoveStream(message: string) {
	const url = new URL('http://localhost:8123/api/ai/love_app/chat/sse/emitter');
	url.searchParams.set('message', message);
	url.searchParams.set('chatId', chatId.value);

	const es = new EventSource(url.toString());
	roomRef.value?.append('ai', '');

	const onMessage = (ev: MessageEvent) => {
		// Spring WebFlux 默认每条 data: xxx\n\n
		const data = ev.data || '';
		if (data === '[DONE]') {
			cleanup();
			roomRef.value?.endStream();
			return;
		}
		roomRef.value?.appendAiChunk(data);
	};

	const onError = () => {
		cleanup();
		roomRef.value?.endStream();
	};

	function cleanup() {
		es.removeEventListener('message', onMessage as any);
		es.removeEventListener('error', onError as any);
		es.close();
	}

	es.addEventListener('message', onMessage as any);
	es.addEventListener('error', onError as any);

	return () => cleanup();
}
</script>

<style scoped>
</style>


